/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';
import { ChildLineCommandProps } from './types';
import { usePointContext } from './PointContext';

type FormDataType = {
  plane: pickedFaceData;
  h: number;
  v: number;
  point?: pickedVertexData;
};

export function PointPlane({
  onClose,
  props,
  editDxid,
}: ChildLineCommandProps) {
  const [formData, setFormData] = useState<FormDataType>({
    plane: undefined,
    v: 0,
    h: 0,
    point: undefined,
  });

  const { picker } = useTools();
  const { setSharedPoint } = usePointContext();

  useEffect(() => {
    excuteData();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const plane = props?.params?.plane;
      const v = props?.params?.v;
      const h = props?.params?.h;
      const point = props?.params?.point;

      await initEditDependency([plane]);

      const defaultPlane = plane
        ? (picker.generatePickObjByPickID(plane) as pickedFaceData)
        : undefined;
      const defaultV = v ? v : 0;
      const defaultH = h ? h : 0;
      const defaultPoint =
        point !== 'ORIGIN'
          ? (picker.generatePickObjByPickID(point) as pickedVertexData)
          : undefined;
      setFormData({
        plane: defaultPlane,
        v: defaultV,
        h: defaultH,
        point: defaultPoint,
      });
    }
  }, [editDxid]);

  const checkAndFinishDraw = async () => {
    const { plane, v, h } = formData;
    if (isEmpty(plane) || v === null || h === null) return;

    await excuteData(false);

    onClose();
  };

  const {
    previewCmdResult,
    initEditDependency,
    initingEdit,
    clear,
    confirmCommand,
  } = useCommand('cmd-point-plane', {
    onClose,
    finishDraw: checkAndFinishDraw,
    commandName: 'CreateVertex',
    editDxid: editDxid || props?.shape,
  });

  useEffect(() => {
    const pointdata = previewCmdResult?.data?.[0]?.points?.[0];
    if (pointdata) {
      setSharedPoint(pointdata);
    } else {
      setSharedPoint(null);
    }
  }, [previewCmdResult]);

  const isFormDataValid = () => {
    const { plane, v, h } = formData;
    return plane != null && v != null && h != null;
  };

  const excuteData = async (preview: boolean = true) => {
    const { plane, v, h, point } = formData;
    if (isEmpty(plane) || v === null || h === null) {
      clear();
      return;
    }

    const pointValue = point ? point.vertexId : 'ORIGIN';

    const allParma = {
      a: {
        mode: 'onplane',
        plane: plane.meshId,
        v: v,
        h: h,
        point: pointValue,
      },
      p: preview,
    };

    await confirmCommand(allParma, preview);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      plane: {
        type: 'string',
        format: PickInputRJSFFormat.PickPlane,
      },
      v: {
        type: 'number',
        title: 'v',
        default: 0,
        format: NumberInputFormat.Length,
      },
      h: {
        type: 'number',
        title: 'h',
        default: 0,
        format: NumberInputFormat.Length,
      },
      point: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      disabled={initingEdit}
      onCancel={onClose}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        const data = {
          v: v.v,
          h: v.h,
          plane: v.plane,
          point: v.point,
        };
        setFormData(data);
      }}
      extraUiSchema={{
        plane: {
          'ui:placeholder': '请输入参考面',
          'ui:autofocus': true,
        },
        v: {
          'ui:placeholder': '请输入v',
        },
        h: {
          'ui:placeholder': '请输入h',
        },
        point: {
          'ui:placeholder': '参考点(默认平面中心点)',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}
